package com.npy.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.npy.reggie.Uilts.ValidateCodeUtils;
import com.npy.reggie.doman.R;
import com.npy.reggie.doman.User;
import com.npy.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        log.info("phone{}",user);

        String phone = user.getPhone();

        if (phone!=null){
            String code = ValidateCodeUtils.generateValidateCode4String(4);

            request.getSession().setAttribute("phone",phone);

            request.getSession().setAttribute("code",code);

            log.info("验证码为：  {}",code);

            return  R.success("验证码发送成功");
        }

        return R.error("手机号有误");
    }

    @PostMapping("/login")

    public R<String> UserLogin(@RequestBody Map<String,String> map, HttpServletRequest request){
        HttpSession session = request.getSession();

        log.info("Map登录接收到的数据{}",map);

        /*log.info("{}",(String)session.getAttribute("phone"));
        log.info("{}",(String)session.getAttribute("code"));
        log.info("{}",map.get("phone"));
        log.info("{}",map.get("code"));
        log.info("---------------");

        log.info("{}", ((String) session.getAttribute("phone")).equals(map.get("phone")));
        log.info("{}", ((String) session.getAttribute("code")).equalsIgnoreCase(map.get("code")));*/

        if (((String)session.getAttribute("phone")).equalsIgnoreCase(map.get("phone"))
                &&((String)session.getAttribute("code")).equalsIgnoreCase((map.get("code")))){
            User user = new User();

            if (userService.list(new QueryWrapper<User>().lambda().
                    eq(map.get("phone")!=null,User::getPhone,map.get("phone"))).size()==0){

                user.setPhone(map.get("phone"));

                userService.save(user);

            }else {
               user= userService.getOne(new QueryWrapper<User>()
                        .lambda().eq(map.get("phone")!=null,User::getPhone,map.get("phone")));

            }
            log.info("save 后 id 是否有值{}", user.getId());

            session.setAttribute("user",user.getId());

            return R.success("登陆成功");

        }

        return R.error("登录失败 验证码错误 或手机号更改过");
    }
}
